<template>
	<view class="box">
		<view class="row">
			<text>手机号</text>
			<input type="text" v-model="phone" maxlength="12"/>
		</view>
		<view class="row">
			<view class="send">
				<button size="mini" class="captcha" :disabled="!codeTag" @click="sendCode">验证码</button>
				<text>{{second}}</text>
			</view>
			<input type="text" v-model="code"  placeholder="- - - -" maxlength="4" />
		</view>
		<view class="row">
			<text style="font-size: 23rpx;">收不到验证码？试试 <text style="color:#00BB00;font-size: 23rpx;"> 语音验证</text></text>
			<!--   -->
			<button @click="doLogin" type="primary" :disabled="!loginTag" style="width: 90%;border-radius: 80rpx;margin-top: 50rpx;">登录</button>
		</view>
		<view class="row">
			<text style="color: #006699;text-align: center;" >通过微信授权登录</text>
		</view>
	</view>
</template>

<script>
	export default{
		data(){
			return{
				code:"",
				phone:"",			//手机号
				codeTag:false,		//是否可以发送验证码：false 不可以；true 可以
				phoneTag:false,		//手机号是否合法 
				loginTag:false,		//登录按钮是否可用：false 不可用；true  可用
				second:"",			//倒计时
			}
		},
		watch:{
			phone:function(val){
				var result= /^1[3456789]\d{9}$/.test(val);
				this.codeTag=result;
				this.phoneTag=result;		
			},
			code:function(val){
				if(val.length==4 && this.phoneTag){
					this.loginTag=true;
				}
			}
			
		},
		methods:{
			//发送验证码
			async sendCode(){
				this.codeTag=false;		//禁用发送验证码button
				this.second=59;
				var timer=setInterval(()=>{
					this.second-=1;
					if(this.second==0){
						clearInterval(timer);
						this.codeTag=true;
						this.second=""
					}
				},1000)
				
				//发送验证码
				var result =await this.$http("/api/sms",{phone:this.phone}).catch(err=>{
					console.error(err)
				})
				//把验证码存储到本地
				uni.setStorageSync("code",result.data.list.code);		
				
			},
			//执行登录
			async doLogin(){
				// 验证用户输入的验证码是否正确：
				var code=uni.getStorageSync("code");		//本地缓存中的验证码
				if(this.code==code){
					//验证码正确，执行登录，获取token
					var result =await this.$http("/api/wxlogin",{phone:this.phone}).catch(err=>{
						console.error(err)
					})
					//把返回的信息存储到本地
					uni.setStorageSync("userInfo",result.data.list)
					
					//页面跳转
					uni.reLaunch({
						url:"/pages/mine/mine"
					})
				}else{
					uni.showToast({
						title:"验证码错误",
						icon:"none"
					})
				}
			}
		}
	}
</script>

<style>
	/* 导入外部的样式文件 */
	/* @import url("../../common/css/index.css"); */
	.box{
		position: relative;
	}

	.row{
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		margin: 40rpx;
	}
	.send{
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.send button{
		margin: 0;
	}
	.send text:nth-of-type(2){
		color: #00BB00;
	}
	text{
		font-size: 27rpx;
		margin-bottom: 10rpx;
	}
	input{
		border-bottom: 1rpx solid gray;
		height: 65rpx;
	}
	.captcha{
		background: #007cfe;
		color: white;
		padding: 10rpx 20rpx;
		border-radius: 13rpx;
	}
</style>
